import { useEffect, useState } from 'react';
import { request } from 'umi';
import { Tree, message, Modal, Form, Input, Cascader } from 'antd';

const { useForm } = Form;
interface IAreaItem {
  areaId: number;
  areaName: string;
  key: string;
  parentId: number;
  level: number;
  areas?: any;
  children?: IAreaItem[];
}
let originAreaList:IAreaItem[] = [];
const SysArea = () => {
  const [areaList, setAreaList] = useState<IAreaItem[]>([]);
  const [searchText, setSearchText] = useState('');
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchAreaList, setSearchAreaList] = useState<IAreaItem[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [currentArea, setCurrentArea] = useState<IAreaItem>({} as IAreaItem);
  const [form] = useForm();

  function findParent(
    array: Array<IAreaItem>,
    item: IAreaItem,
  ): IAreaItem | undefined {
    for (let i = 0; i < array.length; i++) {
      if (array[i].areaId === item.parentId && array[i].level < item.level) {
        return array[i];
      }
      if (array[i].children) {
        let result = findParent(array[i].children!, item);
        if (result) {
          return result;
        }
      }
    }
  }
  useEffect(() => {
    getAreaList();
  }, []);

  function hasSearchdAreaName(
    { children }: IAreaItem,
    searchText: string,
  ): boolean {
    if (!children) return false;
    for (let i = 0; i < children!.length; i++) {
      if (children![i].areaName.indexOf(searchText) !== -1) {
        return true;
      }
      if (children![i].children) {
        let result = hasSearchdAreaName(children![i], searchText);
        if (result) {
          return result;
        }
      }
    }
    return false;
  }

  function filterSearchdAreaName(
    children: IAreaItem[],
    searchText: string,
  ): IAreaItem[] {
    return children!
      .map((item) => {
        if (
          item.areaName.indexOf(searchText) !== -1 ||
          hasSearchdAreaName(item, searchText)
        ) {
          if (item.children) {
            item.children = filterSearchdAreaName(
              item.children!,
              searchText,
            ) as IAreaItem[];
            return item;
          } else {
            return item;
          }
        } else {
          return undefined;
        }
      })
      .filter((item) => item) as IAreaItem[];
  }

  useEffect(() => {
    // 计算searchAreaList
    if (searchText) {
      let searchAreaList = filterSearchdAreaName(areaList, searchText);
      setSearchAreaList(searchAreaList);
    }
  }, [searchText]);

  function getKeys(array: IAreaItem[]): string[] {
    const keys: string[] = [];
    for (let i = 0; i < array.length; i++) {
      keys.push(array[i].key);
      if (array[i].children) {
        keys.push(...getKeys(array[i].children!));
      }
    }
    return keys;
  }

  useEffect(() => {
    if (searchAreaList.length && searchText) {
      setExpandedKeys(getKeys(searchAreaList) as never[]);
    }
  }, [searchAreaList, searchText]);
  function getAreaList() {
    request('/admin/area/list').then((res) => {
      originAreaList = res;
      const areaList: IAreaItem[] = [];
      res.sort((a,b)=>a.level-b.level);
      res.forEach((item: IAreaItem) => {
        item.key = String(item.areaId);
        let parent = findParent(areaList, item);
        if (parent) {
          parent.children = parent.children || [];
          parent.children.push(item);
        } else {
          areaList.push(item);
        }
      });
      setAreaList(areaList);
    });
  }
  async function deleteArea({ areaId }: IAreaItem) {
    try {
      await request(`/admin/area/${areaId}`, { method: 'DELETE' });
      message.success('删除成功');
      getAreaList();
    } catch {
      message.error('删除失败');
    }
  }

  async function editArea() {
    let {editParentId} = form.getFieldsValue();
    const {areaId, areaName, level} = currentArea;
    const parentId = editParentId.pop();
    let parentIndex = originAreaList.findIndex(item=>item.areaId === parentId);
    const data = {
      areaId,
      areaName,
      area: null,
      level: originAreaList[parentIndex].level+1,
      parentId
    }
    try {
      await request(`/admin/area`, { method: 'PUT', data });
      message.success('编辑成功');
      getAreaList();
      setShowModal(false);
    } catch {
      message.error('删除失败');
    }
  }
  console.log('currentArea...', currentArea);
  return (
    <>
      <p>地址管理</p>
      <input
        type="text"
        value={searchText}
        onChange={(e) => setSearchText(e.target.value)}
      />
      <Tree
        treeData={searchText ? searchAreaList : areaList}
        // expandedKeys={expandedKeys}
        titleRender={(nodeData) => {
          return (
            <div>
              <span>{nodeData.areaName}</span>
              <p>
                <button
                  onClick={() => {
                    setCurrentArea(nodeData);
                    form.setFieldsValue(nodeData);
                    setShowModal(true);
                  }}
                >
                  修改
                </button>
                <button onClick={() => deleteArea(nodeData)}>删除</button>
              </p>
            </div>
          );
        }}
      />
      <Modal
        key={JSON.stringify(currentArea)}
        title="修改"
        visible={showModal}
        onOk={editArea}
        onCancel={()=>setShowModal(false)}
      >
        <Form initialValues={currentArea} form={form}>
          <Form.Item
            label="地区名称"
            name="areaName"
            rules={[{ required: true, message: '请输入地区名称!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="上级地区"
            name="editParentId"
            rules={[{ required: true, message: '请输入地区名称!' }]}
          >
            <Cascader fieldNames={{label: 'areaName', value: 'areaId'}} options={areaList} placeholder="请选择" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default SysArea;
